package Arduino;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * User: Mike
 * Date: 8/4/12
 */
public class WriteDataToFile {
    private File txtFile;

    public WriteDataToFile(String filePath) {
        this.txtFile = new File(filePath);
    }

    //Write out Files ================================================================
    void WriteData(List<Double> data, List<String> columnNames) throws IOException {
        boolean fileExists = true;
        if (!txtFile.exists())
            fileExists = false;

//            DecimalFormat df1 = new DecimalFormat("###.##");
        FileWriter write = new FileWriter(txtFile.getPath(), true);
        PrintWriter text = new PrintWriter(write, true);

        // write out the header if appropriate
        if (!fileExists) {
            String header = "DateTime" + "\t";
            for (String name : columnNames) {
                header = header + name + "\t";
            }
            text.println(header);
        }

        // write out the data
        String output = CurrentTime() + "\t";
        for (Double datapoint : data) {
            output = output + datapoint.toString() + "\t";
        }
        text.println(output);

        text.flush();
        write.close();
        text.close();
    }

    public static String CurrentTime() {
        Calendar calendar = new GregorianCalendar();

//        String am_pm;
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        if (calendar.get(Calendar.AM_PM) == 0) {
//            am_pm = "AM";
        } else {
            hour = hour + 12;
//            am_pm = "PM";
        }
        month++;
//        Data.dateTimeS = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    }

}
